/*  Copyright 2011 Jason Jones
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.jasonwjones.hyperion.jessub.formattingvalue;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.jasonwjones.hyperion.jessub.formattingvalue.date.DateFormattingValue;
import com.jasonwjones.hyperion.jessub.formattingvalue.env.EnvironmentFormattingValue;

/**
 * Creates formatting values
 * @author jasonwjones
 *
 */
public class FormattingValueFactory {
	
	public FormattingValue create(String formattingValueCode) {	
		if (isFunction("NOW", formattingValueCode)) {
			return DateFormattingValue.createWithNow(getContents("NOW", formattingValueCode));
		} else if (isFunction("ENV", formattingValueCode)) {
			return new EnvironmentFormattingValue(getContents("ENV", formattingValueCode));		
		} 
		return null;
	}
	
	public boolean isFunction(String functionName, String formattingValue) {
		String template = functionName + "\\((.*)\\)";
		return Pattern.compile(template).matcher(formattingValue).matches();
	}
	
	public String getContents(String functionName, String formattingValue) {
		String template = functionName + "\\((.*)\\)";
		Pattern p = Pattern.compile(template);
		Matcher m = p.matcher(formattingValue);
		if (m.find()) {
			return m.group(1);
		}
		return null;
	}
	
}
